package com.example.contentprovider;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.widget.GridView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private ContentResolver resolver;
    private GridView gvImg;
    private List<CustomImage> imageList;
    private ImageAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //获取控件
        gvImg = findViewById(R.id.gv);
        //初始化数据源
        initData();
        //实例化适配器对象
        adapter = new ImageAdapter(
                this,
                R.layout.activity_main_item,
                imageList
        );
        //给adapterview绑定适配器
        gvImg.setAdapter(adapter);




    }

    private void initData() {
        //获取图片
        //1.使用Resolver对象获取系统图片
        //1.1 得到Resolver对象
        resolver = getContentResolver();
        //1.2 调用查询数据的方法（需要有一些参数URI）
        Cursor cursor = resolver.query(Media.EXTERNAL_CONTENT_URI,
                null, null,
                null, null);
        // 2.遍历封装到数据源中
        if (cursor.getCount() != 0){
            Log.i("msg","查询到"+cursor.getCount()+"张图片");
            imageList = new ArrayList<>();
            CustomImage customImage = null;
            while (cursor.moveToNext()){
                //获取图片名称（带有路径的图片名称）
                String file = cursor.getString(cursor.getColumnIndex(Media.DATA));
                //获取图片的体积
                long size = cursor.getLong(cursor.getColumnIndex(Media.SIZE));
                //构造成customImage对象
                customImage = new CustomImage(file,size);
                //封装到数据源
                imageList.add(customImage);
            }
        }


    }
}











